package com.jandan.logic;

import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;

import com.jandan.persistence.iface.WordDao;
import com.jandan.ui.model.CnAndSentence;
import com.jandan.ui.model.Word;

/**
 * 导入词库的工具类
 * <p>
 * 用户上传词库文件后，将会逐行读取文件内容，并将单词的各个字段填写到数组中，在调用此类的方法将单词写入数据库中
 * </p>
 * @author Gong Yong
 * @see com.jandan.web.admin.WordLibFileUploadBean
 * @version 1.0
 */
public class WordImportTool {
	private WordDao wordDao;

	public void setWordDao(WordDao wordDao) {
		this.wordDao = wordDao;
	}
	public void importWords(List<Word> wordList, long wordLibID) {
		for (Iterator<Word> it = wordList.iterator(); it.hasNext();) {
			Word word = it.next();
			wordDao.insertWord(word);
		}
	}

	/**
	 * 将一个单词写到数据库的方法
	 * @param words   包含单词各个字段的字符串数组
	 * @param wordLibID 词库ID
	 */
	public void importWords(String[] words, long wordLibID) {
		List<CnAndSentence> csList = null;
		String[] s = null;
		Word word = null;
		String cnStr = null;
		String senStr = null;
		String[] css = null;
		String[] sss = null;
		CnAndSentence cs = null;
		
		int length = words.length;
		for (int i = 0; i < length; i++) {
			csList = new ArrayList<CnAndSentence>();
			s = words[i].split("\\|");

			word = new Word();
			word.setWordEn(s[0]);
			word.setPhonetics(s[1]);

			if (s.length > 2) {
				cnStr = s[2];
				senStr = null;
				if (cnStr != null) {
					css = cnStr.split("\\t");
					sss = new String[] {};
					if (s.length > 3) {
						senStr = s[3];
						if (senStr != null) {
							sss = senStr.split("\\t");
						}
					}
					for (int j = 0; j < css.length; j++) {
						cs = new CnAndSentence();
						cs.setCn(css[j]);
						if (sss != null) {
							if (sss.length > j
									&& !sss[j].equalsIgnoreCase("none")) {
								cs.setSentence(sss[j]);
							}
						}
						csList.add(cs);
					}
				}
			}
			if (s.length > 4) {
				word.setDescription(s[4]);
			}
			
			word.setCnAndSentenceList(csList);
			word.setWordLibID(wordLibID);
			
			wordDao.insertWord(word);
		}
	}

}
